package cc.rengu.igas.mcps.core.service.trans.cardpay;

import cc.rengu.igas.channel.cups.common.constant.CupsConfigConstant;
import cc.rengu.igas.channel.cups.facade.bean.CupsTermInfo;
import cc.rengu.igas.channel.cups.facade.bean.OrigTxnInfo;
import cc.rengu.igas.channel.cups.facade.request.PreAuthRevsalRequest;
import cc.rengu.igas.channel.cups.facade.response.PreAuthRevsalResponse;
import cc.rengu.igas.mcps.common.constant.McpsParamConstant;
import cc.rengu.igas.mcps.common.constant.McpsTreeNodeConstant;
import cc.rengu.igas.mcps.common.enums.McpsAcctTypeEnum;
import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.core.model.PosTransInfo;
import cc.rengu.igas.mcps.core.realize.PosParamDealService;
import cc.rengu.igas.mcps.core.realize.impl.PosParamDealServiceImpl;
import cc.rengu.igas.mcps.core.service.base.RevsalService;
import cc.rengu.igas.mcps.facade.request.PosCardPreAuthReversalRequest;
import cc.rengu.igas.mcps.facade.response.PosCardPreAuthReversalResponse;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.igas.share.common.util.GlobalEsbUtil;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.model.MchntTermInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.FinanceTxnMapper;
import cc.rengu.oltp.service.common.dao.impl.FinanceTxnMapperImpl;
import cc.rengu.oltp.service.common.entity.*;
import cc.rengu.oltp.service.common.enums.BizStatusEnum;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 预授权冲正服务.
 */
public class PosCardPreAuthRevsalService extends RevsalService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        PosCardPreAuthReversalRequest posCardPreAuthReversalRequest = new PosCardPreAuthReversalRequest();
        ConvertUtil.convertOutput(posCardPreAuthReversalRequest);
        return posCardPreAuthReversalRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        BizResponse bizResponse = new BizResponse();
        PosCardPreAuthReversalResponse posCardPreAuthReversalResponse = new PosCardPreAuthReversalResponse();
        ConvertUtil.convertOutput(posCardPreAuthReversalResponse);
        PosCardPreAuthReversalRequest posCardPreAuthReversalRequest = (PosCardPreAuthReversalRequest) request;
        if (null == txnInfo) {
            rglog.error("从缓存中获取交易配置信息失败");
            throw new BizException(RespCodeEnum.POS_NOT_SUPPORT.getRespCode(), RespCodeEnum.POS_NOT_SUPPORT.getRespDesc());
        }
        String sysNo = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        //获取原交易商户订单
        MchntOrderInfo origMchntOrderInfo = (MchntOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_MCHNT_ORDER_INFO);
        //获取原交易用户订单
        UserOrderInfo origUserOrderInfo = (UserOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_USER_ORDER_INFO);
        //获取原交易esb通道支付订单
        String origSysSeq = origMchntOrderInfo.getSysSeqNum();
        xmlTreeUtil.setXmlTreeStringValue(McpsTreeNodeConstant.ORIG_SYS_SEQ_NO, origSysSeq);
        /*初始化订单服务*/
        OrderService orderService = new OrderServiceImpl();
        PosParamDealService posParamDealService = new PosParamDealServiceImpl();
        //获取原通道支付订单
        PayOrderInfo origPayOrderInfoESB = (PayOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_PAY_ORDER_INFO);

        //获取原流水
        FinanceTxnMapper financeTxnMapper = new FinanceTxnMapperImpl();
        FinanceTxn oriFinanceTxn = financeTxnMapper.selectFinanceTxnInfoByPrimaryKey(origPayOrderInfoESB.getInstId(), origPayOrderInfoESB.getSysSeqNum());
        if (null == oriFinanceTxn) {
            rglog.error("此时为数据库问题导致");
            throw new BizException(OltpRpcdEnum.OLTP_PROCESS_ERROR);
        }

        //异步调用esb银数预授权冲正接口
        if (origPayOrderInfoESB.getPayerAcctType().equals(McpsAcctTypeEnum.OWN_CREDIT.getAcctType())) {
            updcPreAuthRevsal(oriFinanceTxn, origPayOrderInfoESB, origUserOrderInfo, origMchntOrderInfo,
                    posCardPreAuthReversalRequest, bizResponse, posParamDealService);
        }
        //异步调用银联预授权冲正接口
        if (origPayOrderInfoESB.getPayerAcctType().equals(McpsAcctTypeEnum.OTHER_DEBIT.getAcctType()) || origPayOrderInfoESB.getPayerAcctType().equals(McpsAcctTypeEnum.OTHER_CREDIT.getAcctType())) {
            cupsPreAuthRevsal(oriFinanceTxn, origPayOrderInfoESB, origUserOrderInfo, origMchntOrderInfo,
                    posCardPreAuthReversalRequest, bizResponse, posParamDealService, posCardPreAuthReversalResponse);
        }

        /* 重组响应结果 */
        ConvertUtil.convertOutput(posCardPreAuthReversalResponse);
        posCardPreAuthReversalResponse.setHeader(posCardPreAuthReversalRequest.getHeader());
        //posCardPreAuthReversalResponse.setEpayRrn(sysNo);
        //posCardPreAuthReversalResponse.setIccardDatainf(posCardPreAuthReversalRequest.getIccardDatainf());
//        posCardPreAuthReversalResponse.setReferenceNo();
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        bizResponse.setResult(posCardPreAuthReversalResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        PosCardPreAuthReversalResponse posCardPreAuthReversalResponse = (PosCardPreAuthReversalResponse) bizResponse.getResult();
        posCardPreAuthReversalResponse.setRespCode(bizResponse.getRespCode());
        posCardPreAuthReversalResponse.setRespDesc(bizResponse.getRespDesc());
        ConvertUtil.convertInput(posCardPreAuthReversalResponse);
    }

    /*
     * 调用银数冲正
     * */
    private void updcPreAuthRevsal(FinanceTxn oriFinanceTxn, PayOrderInfo oriPayOrderInfoESB, UserOrderInfo origUserOrderInfo,
                                   MchntOrderInfo origMchntOrderInfo, PosCardPreAuthReversalRequest posCardPreAuthReversalRequest,
                                   BizResponse bizResponse, PosParamDealService posParamDealService) throws Exception {
        DubboService dubboService = new DubboServiceImpl();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        OrderService orderService = new OrderServiceImpl();
        String instId = posCardPreAuthReversalRequest.getHeader().getInstId();
        String sysNum = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.SYS_SEQ_NUM);
        // TODO 银数 预授权完成冲正
        // (1) 通讯级失败，返回失败
        // （2） 交易成功，更新原订单表已冲正，返回成功
        // （3） 交易超时，返回超时

    }

    /*
     * 调用银联冲正
     * */
    private void cupsPreAuthRevsal(FinanceTxn oriFinanceTxn, PayOrderInfo oriPayOrderInfoESB, UserOrderInfo origUserOrderInfo,
                                   MchntOrderInfo origMchntOrderInfo, PosCardPreAuthReversalRequest posCardPreAuthReversalRequest,
                                   BizResponse bizResponse, PosParamDealService posParamDealService,
                                   PosCardPreAuthReversalResponse posCardPreAuthReversalResponse) throws Exception {
        DubboService dubboService = new DubboServiceImpl();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        OrderService orderService = new OrderServiceImpl();
        String instId = posCardPreAuthReversalRequest.getHeader().getInstId();
        String sysNum = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.SYS_SEQ_NUM);
        /*获取商户基本信息*/
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(instId, posCardPreAuthReversalRequest.getMchntNo());
        if (null == mchntInfo) {
            rglog.error("查询商户基本信息失败<{}>", posCardPreAuthReversalRequest.getMchntNo());
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        /*准备请求报文*/
        PreAuthRevsalRequest preAuthRevsalRequest = new PreAuthRevsalRequest();
        /*设置请求报文*/
        cc.rengu.igas.channel.cups.facade.base.Header header = new cc.rengu.igas.channel.cups.facade.base.Header();
        BeanUtil.beanCopy(posCardPreAuthReversalRequest.getHeader(), header);
        header.setVersion("1.0.0");
        ChannelCallCfg channelCallCfgList = txnInfo.getChannelCallCfgList().stream().filter(item -> ChannelEnum.CUPS.getChannelType().equals(item.getCallChannelId())).collect(Collectors.toList()).get(0);
        /*通道交易码*/
        header.setTxnNum(channelCallCfgList.getCallChannelTxn());
        header.setTraceNo(GlobalEsbUtil.generateEsbSeqeuenceNumber(instId));
        header.setTransDate(oriFinanceTxn.getTxnDate());
        header.setTransTime(oriFinanceTxn.getTxnTime());
        preAuthRevsalRequest.setHeader(header);
        preAuthRevsalRequest.setCupsTraceNo(sysNum.substring(sysNum.length() - 6));
        String txnDate = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_DATE);
        String txnTime = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_TIME);
        preAuthRevsalRequest.setTransDateTime(txnDate.substring(4, 8) + txnTime);
        preAuthRevsalRequest.setCupsMchntNo(mchntInfo.getCupsMchntNo());
        preAuthRevsalRequest.setMchntNo(preAuthRevsalRequest.getMchntNo());
        preAuthRevsalRequest.setTermNo(posCardPreAuthReversalRequest.getTermNo());
        preAuthRevsalRequest.setMchntShortName(mchntInfo.getMchntSimpleName());
        preAuthRevsalRequest.setMchntType(mchntInfo.getIndustryType());
        String acqInstCode = posParamDealService.genCupsAcqInstCode(instId, posCardPreAuthReversalRequest.getMchntNo());
        String fwdInstCode = XmlConfigUtil.getXmlConfigCacheKeyValue(CupsConfigConstant.CUPS_CONF_NODE, CupsConfigConstant.CUPS_FWD_INS_CODE);
        preAuthRevsalRequest.setCupsInstCode(acqInstCode);
        preAuthRevsalRequest.setFwdInstCode(fwdInstCode);
        preAuthRevsalRequest.setOrderAmt(oriPayOrderInfoESB.getRealPayAmt());
        preAuthRevsalRequest.setOrderCcy(McpsParamConstant.INNER_DEFAULT_ORDERCCY);
        preAuthRevsalRequest.setPayAcctNo(oriPayOrderInfoESB.getPayerAcctInfo());
        preAuthRevsalRequest.setAuthCode(oriPayOrderInfoESB.getTxnAuthCode());
        //TODO 待修改
        String posTransString = new String(Base64.decodeBase64(oriPayOrderInfoESB.getPayerRemark()));
        PosTransInfo posTransInfo = JSON.parseObject(posTransString, PosTransInfo.class);
        preAuthRevsalRequest.setReferenceNo(posTransInfo.getRefNo());
        preAuthRevsalRequest.setEntryMode(posTransInfo.getEntryMode());
        preAuthRevsalRequest.setCardSeqNo(posTransInfo.getCardSeqNo());
        preAuthRevsalRequest.setIcConCode(posTransInfo.getIcConCode());
        preAuthRevsalRequest.setTermRead(posTransInfo.getTermRead());
        preAuthRevsalRequest.setIcData(posTransInfo.getIcData());
        /*设置终端信息*/
        CupsTermInfo cupsTermInfo = new CupsTermInfo();
        BeanUtil.beanCopy(posCardPreAuthReversalRequest.getTermInfo(), cupsTermInfo);
        if (StringUtil.isEmptyOrNull(cupsTermInfo.getDeviceType())) {
            MchntTermInfo mchntTermInfo = mchntService.getMchntTermInfo(instId, posCardPreAuthReversalRequest.getMchntNo(), posCardPreAuthReversalRequest.getTermNo());
            cupsTermInfo.setDeviceType(mchntTermInfo.getTermType());
        }
        preAuthRevsalRequest.setTermInfo(cupsTermInfo);
        /*设置原交易信息*/
        OrigTxnInfo origTxnInfo = new OrigTxnInfo();
        origTxnInfo.setOriTraceNo(oriPayOrderInfoESB.getChannelOrderId());
        origTxnInfo.setOriTxnDate(oriPayOrderInfoESB.getTxnDate());
        origTxnInfo.setOriTransDateTime(oriPayOrderInfoESB.getTxnDate().substring(4, 8) + oriPayOrderInfoESB.getTxnTime());
        origTxnInfo.setOriCupsTraceNo(oriPayOrderInfoESB.getSysSeqNum().substring(sysNum.length() - 6, sysNum.length()));
        preAuthRevsalRequest.setOrigTxnInfo(origTxnInfo);
        posCardPreAuthReversalResponse.setReferenceNo(preAuthRevsalRequest.getReferenceNo());
        cc.rengu.igas.channel.cups.facade.result.Result<PreAuthRevsalResponse> result = (cc.rengu.igas.channel.cups.facade.result.Result<PreAuthRevsalResponse>) dubboService.callDubboService("cupsPayService", "preAuthRevsal", preAuthRevsalRequest);
        rglog.debug("dubbo调用银行卡预授权冲正结果：{}", JSON.toJSONString(result));
        /*冲正失败处理*/
        if (null == result || null == result.getResult() || (!result.getResult().getRespCode().equals(McpsParamConstant.DUBBO_SUCCESS) && !result.getResult().getRespCode().equals(McpsParamConstant.DUBBO_OVERTIME) && !McpsParamConstant.COMMUNICATION_OVERTIME.equals(result.getResult().getRespCode()))) {
            bizResponse.setRespCode(RespCodeEnum.TRANS_FAIL.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_FAIL.getRespDesc());
        } else if (result.isSuccess() && McpsParamConstant.DUBBO_SUCCESS.equals(result.getResult().getRespCode())) {
            List<MchntOrderInfo> oriMchntOrderInfoList = new ArrayList<>();
            //更新原支付订单表已冲正
            oriPayOrderInfoESB.setSettleDate(result.getResult().getSettleDate());
            oriPayOrderInfoESB.setBizStatus(BizStatusEnum.REVSAL.getStatus());
            //更新原商户订单表已冲正
            origMchntOrderInfo.setBizStatus(BizStatusEnum.REVSAL.getStatus());
            oriMchntOrderInfoList.add(origMchntOrderInfo);
            //更新原用户订单表已冲正
            origUserOrderInfo.setBizStatus(BizStatusEnum.REVSAL.getStatus());
            orderService.updateOrderInfo(origUserOrderInfo, oriMchntOrderInfoList, oriPayOrderInfoESB);
            bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        } else {
            bizResponse.setRespCode(RespCodeEnum.POS_RSP_TIME_OUT.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.POS_RSP_TIME_OUT.getRespCode());
        }
    }
}
